//
//  ListCtrl.swift
//  yiplayer
//
//  Created by cgw on 2024/5/13.
//

import UIKit

class ListCtrl: UITableViewController {
    
    var datas: [YiSong]?
    var hud: BLProgressHUD?
    var key: String = "今天"
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        self.tableView.register(ListCell.self, forCellReuseIdentifier: "reuseIdentifier")
        self.tableView.rowHeight = 50.0
        self.view.backgroundColor = .white
        
        weak var weakSelf = self
        YIHttp.neteaseSearch(caller: self, keyword: self.key) { data, err in
     
            //weakSelf?.hud?.hide()
            if err != nil {
                weakSelf?.showError(err:err)
            }
            else{
                weakSelf?.datas = data as? [YiSong]
                weakSelf?.tableView.reloadData()
            }
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return datas?.count ?? 0
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! ListCell

        // Configure the cell...
        let m = self.model(datas, indexPath) as? YiSong
        cell.nameL.text = m?.name

        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        if let m = self.model(datas, indexPath) as? YiSong {
            
            ActionSheet.title("确认下载【"+m.name!+"】吗?").action("确认") {
                self.download(indexPath: indexPath, model: m)
            }.cancel("取消").show()
        }
    }
    
    func download(indexPath: IndexPath, model: YiSong) {
        weak var weakSelf = self
        hud = self.showHud()
        YIHttp.neteaseMp3Url(caller: self, songId: model.id) { data, err in
            weakSelf?.hud?.hide()
            if err != nil {
                weakSelf?.showError(err: err)
            }
            else{
                if let d = data as? (String, Int, Int) {
                    let ul = d.0
                    //let br = d.1
                    let size = d.2
                    model.song_url = ul
                    model.size = size 
                    weakSelf?.startDownload(indexPath: indexPath, model: model)
                }else{
                    weakSelf?.showErrorMsg("获取mp3地址失败")
                }   
            }
        }
    }
    
    func startDownload(indexPath: IndexPath, model: YiSong) {
        weak var weakSelf = self
        hud = self.showHud()
        let m = model
        YIHttp.downloadNeteaseMp3(song: m) { pro in
            
        } complete: { filepath, err in
            weakSelf?.hud?.hide()
            if err != nil {
                weakSelf?.showError(err: err)
            }
            else{
                weakSelf?.showSuccess("下载完成")
                print("路径：")
                print(YiFilePath.share.songDir)
                
                let ul = NSURL.fileURL(withPath: filepath as! String)
//                BLVideoPlayer.play(withURL: ul, inCtrl: self)
            }
        }
    }
}

class ListCell: UITableViewCell {
    let nameL = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        nameL.font(15).color(Color3).addTo(self.contentView).makeCons { make in
            make.left.equal(15.0)
            make.right.equal(-20)
            make.top.bottom.equal(0)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
